package com.netty4.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {
    //private final ByteBuf firstMessage;
    private int counter;
    byte [] bytes;
    public TimeClientHandler(){
        bytes = ("ORDER"+ System.getProperty("line.separator")).getBytes();
        //firstMessage = Unpooled.buffer(bytes.length);
        //firstMessage.writeBytes(bytes);
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf;
        for (int i = 0; i < 100; i++) {
            byteBuf = Unpooled.buffer(bytes.length);
            byteBuf.writeBytes(bytes);
            ctx.writeAndFlush(byteBuf);
        }
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /*ByteBuf byteBuf = (ByteBuf) msg;
        byte [] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String body = new String(bytes,"UTF-8");*/
        String body = (String)msg;
        System.out.println("now time is "+body+" counter="+ ++counter);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
